import 'dart:async';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:xrenovation/api/auth.api.dart';
import 'package:xrenovation/localization/app_localizations.dart';
import 'package:xrenovation/routes.dart';
import 'package:xrenovation/utils/message_util.dart';
import 'package:xrenovation/widgets/custom_button.dart';
import 'package:xrenovation/widgets/custom_text_field.dart';

class RegisterPage extends StatefulWidget {
  const RegisterPage({super.key});

  @override
  State<RegisterPage> createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  final _formKey = GlobalKey<FormState>();
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();
  final _usernameController = TextEditingController();
  final _phoneController = TextEditingController();
  final _cityController = TextEditingController();
  final _codeController = TextEditingController();
  final List<TextEditingController> _codeControllers = List.generate(4, (index) => TextEditingController());

  String? _selectedCountry = 'US';
  String? _selectedState;
  List<Map<String, dynamic>> _countries = [];
  List<Map<String, dynamic>> _states = [];

  bool _isLoadingCountries = false;
  bool _isLoadingStates = false;
  bool _isSendingCode = false;
  bool _isRegistering = false;
  bool _showCodeInput = false;
  bool _countryValid = true;
  bool _stateValid = true;

  @override
  Widget build(BuildContext context) {
    final localizations = AppLocalizations.of(context);
    final theme = Theme.of(context);
    final isWideScreen = MediaQuery.of(context).size.width >= 1024;

    return Scaffold(
      body: GestureDetector(
        onTap: () => FocusScope.of(context).unfocus(),
        behavior: HitTestBehavior.opaque,
        child:
            isWideScreen
                ? _buildWideLayout(context, localizations, theme)
                : _buildNarrowLayout(context, localizations, theme),
      ),
    );
  }

  @override
  void dispose() {
    _emailController.dispose();
    _passwordController.dispose();
    _usernameController.dispose();
    _phoneController.dispose();
    _cityController.dispose();
    _codeController.dispose();
    for (var controller in _codeControllers) {
      controller.dispose();
    }
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    _loadCountries().then((_) {
      if (_selectedCountry != null) {
        _loadStates(_selectedCountry);
      }
    });
  }

  Widget _buildDivider(double height, Color color, double width) {
    return Container(height: height, width: width, color: color);
  }

  Widget _buildDropdownButton({
    required String? value,
    required String hint,
    required List<Map<String, dynamic>> items,
    required bool isLoading,
    required Function(String?) onChanged,
    bool enabled = true,
    bool isValid = true,
  }) {
    final theme = Theme.of(context);

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12),
      decoration: BoxDecoration(
        border: Border.all(color: !isValid ? theme.colorScheme.error : theme.colorScheme.outline.withOpacity(0.5)),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        children: [
          Expanded(
            child: DropdownButton<String>(
              value: value,
              hint: Text(
                hint,
                style: theme.textTheme.bodyMedium?.copyWith(color: theme.colorScheme.onSurface.withOpacity(0.4)),
              ),
              isExpanded: true,
              underline: const SizedBox(),
              items:
                  items.map((item) {
                    return DropdownMenuItem<String>(value: item['regionId'], child: Text(item['nameEn']));
                  }).toList(),
              onChanged: enabled ? onChanged : null,
            ),
          ),
          if (isLoading)
            const Padding(
              padding: EdgeInsets.only(left: 8),
              child: SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2)),
            ),
        ],
      ),
    );
  }

  Widget _buildFeatureItem(String text) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Icon(Icons.check_circle, color: Colors.white.withOpacity(0.9), size: 16),
        const SizedBox(width: 8),
        Expanded(child: Text(text, style: TextStyle(fontSize: 14, height: 1.71, color: Colors.white.withOpacity(0.9)))),
      ],
    );
  }

  Widget _buildFeatureList(AppLocalizations? localizations) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildFeatureItem(localizations!.translate('r_feature1')),
        const SizedBox(height: 16),
        _buildFeatureItem(localizations.translate('r_feature2')),
        const SizedBox(height: 16),
        _buildFeatureItem(localizations.translate('r_feature3')),
      ],
    );
  }

  List<Widget> _buildFormFields(AppLocalizations? localizations, ThemeData theme) {
    if (_showCodeInput) {
      return [
        const SizedBox(height: 60),
        Text(localizations!.translate('one_time_code'), style: theme.textTheme.bodyMedium),
        const SizedBox(height: 10),
        LayoutBuilder(
          builder: (context, constraints) {
            final containerWidth = constraints.maxWidth;
            final calculatedHeight = containerWidth * 26 / 327;
            final double containerHeight = calculatedHeight < 44 ? 44 : calculatedHeight;
            final dividerColor = theme.dividerColor;
            final borderWidth = 1.0;

            return SizedBox(
              height: containerHeight,
              child: Stack(
                children: [
                  Container(
                    decoration: BoxDecoration(
                      border: Border.all(color: dividerColor, width: borderWidth),
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  Row(
                    children: List.generate(4, (index) {
                      return Expanded(
                        child: Center(
                          child: TextFormField(
                            controller: _codeControllers[index],
                            maxLength: 1,
                            keyboardType: TextInputType.number,
                            textAlign: TextAlign.center,
                            style: TextStyle(fontSize: containerHeight * 0.5, color: theme.textTheme.bodyMedium?.color),
                            decoration: InputDecoration(
                              counterText: '',
                              border: InputBorder.none,
                              focusedBorder: InputBorder.none,
                              enabledBorder: InputBorder.none,
                              errorBorder: InputBorder.none,
                              disabledBorder: InputBorder.none,
                              contentPadding: EdgeInsets.zero,
                              fillColor: Colors.transparent,
                              filled: true,
                            ),
                            onChanged: (value) {
                              if (value.length == 1 && index < 3) {
                                FocusScope.of(context).nextFocus();
                              } else if (value.isEmpty && index > 0) {
                                FocusScope.of(context).previousFocus();
                              }
                              _codeController.text = _codeControllers.map((c) => c.text).join();
                            },
                          ),
                        ),
                      );
                    }),
                  ),
                  Positioned(
                    left: containerWidth * 0.25,
                    child: _buildDivider(containerHeight, dividerColor, borderWidth),
                  ),
                  Positioned(
                    left: containerWidth * 0.5,
                    child: _buildDivider(containerHeight, dividerColor, borderWidth),
                  ),
                  Positioned(
                    left: containerWidth * 0.75,
                    child: _buildDivider(containerHeight, dividerColor, borderWidth),
                  ),
                ],
              ),
            );
          },
        ),
        const SizedBox(height: 10),
        Text(
          localizations.translate('code_sent_prompt'),
          style: theme.textTheme.bodySmall?.copyWith(color: theme.hintColor),
        ),
        const SizedBox(height: 20),
        CustomButton(title: localizations.translate('sign_up'), isLoading: _isRegistering, onTap: _handleRegister),
      ];
    } else {
      return [
        CustomTextField(
          label: localizations!.translate('email'),
          labelMark: true,
          controller: _emailController,
          hintText: localizations.translate('email_hintText'),
          keyboardType: TextInputType.emailAddress,
          hiddenErrorTip: true,
          validator: (value) {
            if (value == null || value.trim().isEmpty) {
              return '';
              // return localizations.translate('email_required');
            }
            if (!RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(value)) {
              return '';
              // return localizations.translate('email_invalid');
            }
            return null;
          },
        ),
        const SizedBox(height: 20),
        CustomTextField(
          label: localizations.translate('password'),
          labelMark: true,
          controller: _passwordController,
          keyboardType: TextInputType.visiblePassword,
          hintText: localizations.translate('pwd_hintText'),
          obscureText: true,
          validator: (value) {
            if (value == null || value.trim().isEmpty) {
              // return '';
              return localizations.translate('password_required');
            }
            if (value.length < 8 || !RegExp(r'^(?=.*[a-z])(?=.*\d).+$').hasMatch(value)) {
              // return '';
              return localizations.translate('password_length');
            }
            return null;
          },
        ),
        const SizedBox(height: 4),
        Text(
          localizations.translate('password_desc'),
          style: theme.textTheme.bodySmall?.copyWith(color: theme.hintColor),
        ),
        const SizedBox(height: 20),
        CustomTextField(
          label: localizations.translate('username'),
          labelMark: true,
          controller: _usernameController,
          keyboardType: TextInputType.name,
          hintText: localizations.translate('username_hintText'),
          hiddenErrorTip: true,
          validator: (value) {
            if (value == null || value.trim().isEmpty) {
              return '';
              // return localizations.translate('username_required');
            }
            return null;
          },
        ),
        const SizedBox(height: 20),
        CustomTextField(
          label: localizations.translate('phone'),
          labelMark: true,
          controller: _phoneController,
          hintText: localizations.translate('phone_hintText'),
          keyboardType: TextInputType.phone,
          hiddenErrorTip: true,
          validator: (value) {
            if (value == null || value.trim().isEmpty) {
              return '';
              // return localizations.translate('phone_required');
            }
            return null;
          },
        ),
        const SizedBox(height: 20),
        CustomTextField(
          label: localizations.translate('city'),
          hintText: localizations.translate('city_hintText'),
          labelMark: true,
          controller: _cityController,
          hiddenErrorTip: true,
          validator: (value) {
            if (value == null || value.trim().isEmpty) {
              return '';
              // return localizations.translate('city_required');
            }
            return null;
          },
        ),
        const SizedBox(height: 20),
        Text('${localizations.translate('country')} *', style: theme.textTheme.bodyMedium),
        const SizedBox(height: 10),
        _buildDropdownButton(
          value: _selectedCountry,
          hint: localizations.translate('select_country'),
          items: _countries,
          isLoading: _isLoadingCountries,
          onChanged: (value) {
            setState(() {
              _selectedCountry = value;
              _loadStates(value);
              _countryValid = value != null;
            });
          },
          isValid: _countryValid,
        ),
        const SizedBox(height: 20),
        Text('${localizations.translate('state')} *', style: theme.textTheme.bodyMedium),
        const SizedBox(height: 10),
        _buildDropdownButton(
          value: _selectedState,
          hint: localizations.translate('select_state'),
          items: _states,
          isLoading: _isLoadingStates,
          onChanged: (value) {
            setState(() {
              _selectedState = value;
              _stateValid = value != null;
            });
          },
          enabled: _selectedCountry != null,
          isValid: _stateValid,
        ),
        const SizedBox(height: 40),
        CustomButton(
          title: localizations.translate('sign_up'),
          isLoading: _isSendingCode,
          onTap: _handleSendVerificationCode,
        ),
      ];
    }
  }

  Widget _buildNarrowLayout(BuildContext context, AppLocalizations? localizations, ThemeData theme) {
    return SingleChildScrollView(
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 40),
        child: _buildRegisterForm(localizations, theme),
      ),
    );
  }

  Widget _buildPromoHeader(AppLocalizations? localizations) {
    return Row(
      children: [
        Image.asset(
          'assets/images/logo.png',
          width: 52,
          height: 52,
          errorBuilder: (context, error, stackTrace) => Icon(Icons.home_work_outlined, size: 52, color: Colors.white),
        ),
        const SizedBox(width: 12),
        Text(
          localizations!.translate('create_account'),
          style: const TextStyle(fontSize: 36, height: 1.11, color: Colors.white, fontWeight: FontWeight.bold),
        ),
      ],
    );
  }

  Widget _buildRegisterForm(AppLocalizations? localizations, ThemeData theme) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Align(
          alignment: Alignment.topRight,
          child: GestureDetector(
            onTap: () => Navigator.pushReplacementNamed(context, AppRoutes.login),
            child: RichText(
              text: TextSpan(
                text: '${localizations!.translate('already_have_account')} ',
                style: theme.textTheme.bodyMedium?.copyWith(color: theme.hintColor),
                children: [
                  TextSpan(
                    text: localizations.translate('sign_in_link'),
                    style: theme.textTheme.bodyMedium?.copyWith(
                      color: theme.colorScheme.primary,
                      fontWeight: FontWeight.w600,
                      decoration: TextDecoration.underline,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
        const SizedBox(height: 40),
        RichText(
          text: TextSpan(
            text: '${localizations.translate('sign_up_to')} ${localizations.translate('app_title')}',
            style: theme.textTheme.headlineSmall?.copyWith(fontWeight: FontWeight.w600),
          ),
        ),
        const SizedBox(height: 10),
        Text(
          localizations.translate('sign_up_description'),
          style: theme.textTheme.bodyMedium?.copyWith(color: theme.hintColor),
        ),
        const SizedBox(height: 20),
        Form(
          key: _formKey,
          autovalidateMode: AutovalidateMode.onUserInteraction,
          child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: _buildFormFields(localizations, theme)),
        ),
        const SizedBox(height: 20),
        _buildTermsAgreement(localizations, theme),
        const SizedBox(height: 40),
      ],
    );
  }

  Widget _buildTermsAgreement(AppLocalizations? localizations, ThemeData theme) {
    return Center(
      child: RichText(
        textAlign: TextAlign.center,
        text: TextSpan(
          text: '${localizations!.translate('terms_agreement')} ',
          style: theme.textTheme.bodySmall?.copyWith(color: theme.hintColor),
          children: [
            TextSpan(
              text: localizations.translate('terms_service'),
              style: theme.textTheme.bodyMedium?.copyWith(
                color: theme.colorScheme.primary,
                decoration: TextDecoration.underline,
              ),
              recognizer: TapGestureRecognizer()..onTap = () => Navigator.pushNamed(context, AppRoutes.termsService),
            ),
            TextSpan(text: localizations.translate('and')),
            TextSpan(
              text: localizations.translate('privacy_policy'),
              style: theme.textTheme.bodyMedium?.copyWith(
                color: theme.colorScheme.primary,
                decoration: TextDecoration.underline,
              ),
              recognizer: TapGestureRecognizer()..onTap = () => Navigator.pushNamed(context, AppRoutes.privacyPolicy),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildWideLayout(BuildContext context, AppLocalizations? localizations, ThemeData theme) {
    return Row(
      children: [
        Expanded(
          flex: 1,
          child: Container(
            padding: const EdgeInsets.all(40),
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/register_bg.png'),
                fit: BoxFit.cover,
                colorFilter: ColorFilter.mode(Colors.black54, BlendMode.darken),
              ),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _buildPromoHeader(localizations),
                const SizedBox(height: 30),
                Text(
                  localizations!.translate('manage_projects'),
                  style: TextStyle(fontSize: 24, height: 1.33, color: Colors.grey[300]),
                ),
                const SizedBox(height: 24),
                _buildFeatureList(localizations),
              ],
            ),
          ),
        ),
        Expanded(
          flex: 1,
          child: SingleChildScrollView(
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 40, vertical: 40),
              child: _buildRegisterForm(localizations, theme),
            ),
          ),
        ),
      ],
    );
  }

  Future<void> _handleRegister() async {
    if (_isRegistering) return;
    if (_codeController.text.trim().length != 4) {
      MessageUtil.error('Please enter 4-digit code');
      return;
    }

    final closeLoading = MessageUtil.loading('Registering...');

    try {
      setState(() => _isRegistering = true);

      final response = await AuthApi.register(
        email: _emailController.text.trim(),
        password: _passwordController.text.trim(),
        username: _usernameController.text.trim(),
        phone: _phoneController.text.trim(),
        city: _cityController.text.trim(),
        state: _selectedState ?? '',
        country: _selectedCountry ?? 'US',
        code: _codeController.text.trim(),
      );

      closeLoading();

      if (response['code'] == 200) {
        MessageUtil.success('Registration successful');
        Navigator.pushReplacementNamed(context, AppRoutes.login);
      } else {
        MessageUtil.error(response['message'] ?? 'Registration failed');
      }
    } catch (e) {
      closeLoading();
      MessageUtil.error('Registration failed');
    } finally {
      if (mounted) setState(() => _isRegistering = false);
    }
  }

  Future<void> _handleSendVerificationCode() async {
    setState(() {
      _countryValid = _selectedCountry != null;
      _stateValid = _selectedState != null;
    });

    if (!(_formKey.currentState?.validate() ?? false)) return;
    if (!_countryValid || !_stateValid) {
      MessageUtil.error('Please fill all required fields');
      return;
    }

    if (_isSendingCode) return;

    final closeLoading = MessageUtil.loading('Sending verification code...');

    try {
      setState(() => _isSendingCode = true);

      final response = await AuthApi.sendRegisterCode(_emailController.text.trim());

      closeLoading();

      if (response['code'] == 200 || response['code'] == 1002) {
        MessageUtil.success('Verification code sent successfully');
        setState(() => _showCodeInput = true);
      } else {
        MessageUtil.error(response['message'] ?? 'Failed to send code');
      }
    } catch (e) {
      closeLoading();
      MessageUtil.error('Failed to send code');
    } finally {
      if (mounted) setState(() => _isSendingCode = false);
    }
  }

  Future<void> _loadCountries() async {
    setState(() => _isLoadingCountries = true);

    try {
      final response = await AuthApi.getCountries();
      setState(() {
        _countries = response;
        if (_countries.isNotEmpty) {
          _selectedCountry =
              _countries.firstWhere(
                (country) => country['regionId'] == 'US',
                orElse: () => _countries.first,
              )['regionId'];
        }
      });
    } catch (e) {
      MessageUtil.error('Failed to load countries');
    } finally {
      setState(() => _isLoadingCountries = false);
    }
  }

  Future<void> _loadStates(String? countryCode) async {
    if (countryCode == null) return;

    setState(() {
      _isLoadingStates = true;
      _selectedState = null;
      _states = [];
    });

    try {
      final response = await AuthApi.getStates(countryCode);
      setState(() {
        _states = response;
      });
    } catch (e) {
      MessageUtil.error('Failed to load states');
    } finally {
      setState(() => _isLoadingStates = false);
    }
  }
}
